package com.wichell.framework.wechat.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Random;

import org.apache.log4j.Logger;

/**   
 * @ClassName:  SignUtils   
 * @Description:签名工具类
 * @author: Isaac
 * @date:   2018年2月12日 上午9:58:07   
 *     
 * @Copyright: 2018 www.wichell.com Inc. All rights reserved.
 */
public final class SignUtils {

	private static final Logger _logger = Logger.getLogger(SignUtils.class);

	private static final String SHA1 = "SHA-1";

	/**   
	 * @Title: checkSignature   
	 * @Description: 验证签名   
	 * @param: @param token
	 * @param: @param signature
	 * @param: @param timestamp
	 * @param: @param nonce
	 * @param: @return      
	 * @return: boolean      
	 * @throws   
	 */
	public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance(SHA1);
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			_logger.error("验签异常:" + e.getMessage());
		} finally {
			content = null;
		}
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**   
	 * @Title: jsapiTicketSha1   
	 * @Description: sha1加密
	 * @param: @param content
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	public static String jsapiTicketSha1(String content) {

		if (_logger.isDebugEnabled()) {
			_logger.debug("加密字符串" + content);
		}
		String signature = null;
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(SHA1);
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			signature = byteToHex(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			_logger.error("jsapiTicketSha1_error：" + e.getMessage());
		}
		content = null;
		return signature;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	/**   
	 * @Title: getRandomString   
	 * @Description: jsapiTicket 16位随机字符串
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	public static String getRandomString() {
		int length = 16;
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuffer sb;
		try {
			Random random = new Random();
			sb = new StringBuffer();
			for (int i = 0; i < length; i++) {
				int number = random.nextInt(base.length());
				sb.append(base.charAt(number));
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			_logger.error("getRandomString_error：" + e.getMessage());
		}
		return null;
	}

	/**   
	 * @Title: byteToStr   
	 * @Description: 将字节数组转换为十六进制字符串
	 * @param: @param byteArray
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**   
	 * @Title: byteToHexStr   
	 * @Description: 将字节转换为十六进制字符串 
	 * @param: @param mByte
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];
		return new String(tempArr);
	}

}
